package com.example.ujsfish.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit单例管理
 * Created by Leon.W on 2019/4/28
 */
public class RetrofitManager {
    private static final String BASE_URL = "http://119.45.26.207:8081/"; //孙老师
    //private static final String BASE_URL = "http://47.101.139.37:8081/";//计算机
    private static RetrofitManager sInstance;
    private Retrofit mRetrofit;
    private RetrofitManager() {
    }
    public static RetrofitManager getInstance() {
        if (null == sInstance) {
            synchronized (RetrofitManager.class) {
                if (null == sInstance) {
                    sInstance = new RetrofitManager();
                }
            }
        }
        return sInstance;
    }

    public static Retrofit getRetrofit() {
        //设置解析时间格式
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

        //设置请求超时
        OkHttpClient.Builder httpBuilder=new OkHttpClient.Builder();

        OkHttpClient client = httpBuilder.readTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS).writeTimeout(15, TimeUnit.SECONDS) //设置超时
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();

        return retrofit;
    }


    public <T> T getApiService( Class<T> service) {

        Retrofit retrofit = getRetrofit();
        //通过java动态代理模式获取代理对象
        T t = retrofit.create(service);
        return t;

    }

}